package com.goldsprite.gameframeworks.ecs.system;

import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.physics.box2d.*;
import com.badlogic.gdx.utils.Array;
import java.lang.invoke.*;

public class CustomPhysicsDebugRenderer extends Box2DDebugRenderer {

    // 添加构造方法
    public CustomPhysicsDebugRenderer() {
        super();
    }

    public CustomPhysicsDebugRenderer(boolean drawBodies, boolean drawJoints, boolean drawAABBs, 
									  boolean drawInactiveBodies, boolean drawVelocities, boolean drawContacts) {
        super(drawBodies, drawJoints, drawAABBs, drawInactiveBodies, drawVelocities, drawContacts);
    }

    private static class MethodHandlesCache {
        static MethodHandle drawShapeHandle;
        static MethodHandle getColorByBodyHandle;
        static boolean initialized = false;

        static {
            try {
                MethodHandles.Lookup lookup = MethodHandles.privateLookupIn(
                    Box2DDebugRenderer.class, 
                    MethodHandles.lookup()
                );

                drawShapeHandle = lookup.findVirtual(
                    Box2DDebugRenderer.class,
                    "drawShape",
                    MethodType.methodType(void.class, Fixture.class, Transform.class, Color.class)
                );

                getColorByBodyHandle = lookup.findVirtual(
                    Box2DDebugRenderer.class,
                    "getColorByBody",
                    MethodType.methodType(Color.class, Body.class)
                );

                initialized = true;
            } catch (Exception e) {
                System.err.println("Static MethodHandle initialization failed: " + e.getMessage());
            }
        }
    }

    @Override
    protected void renderBody(Body body) {
        if (!MethodHandlesCache.initialized) {
            super.renderBody(body);
            return;
        }

        Array<Fixture> fixtures = body.getFixtureList();

        for (Fixture fixture : fixtures) {
            Filter filter = fixture.getFilterData();
            if (filter.maskBits != 0) {
                try {
                    Color color = (Color) MethodHandlesCache.getColorByBodyHandle.bindTo(this)
                        .invokeWithArguments(body);
                    MethodHandlesCache.drawShapeHandle.bindTo(this)
                        .invokeWithArguments(fixture, body.getTransform(), color);
                } catch (Throwable e) {
                    System.err.println("Failed to render fixture: " + e.getMessage());
                }
            }
        }
    }
}
